<html lang="en-US">

<head>
    
<title>为什么 Go 语言把类型放在后面？ - 花落雨忧</title>

<meta property="og:title" content="为什么 Go 语言把类型放在后面？ - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
前段时间看到大家在吵一个话题，那就是 Go 语言的类型声明，抠知识抠的非常细了，就是为什么他要放在后面。
示例代码如下：
[&amp;hellip;] var a []string var b []string 其实在早年 Go 官方估计已经被问烦了，写过一篇《Go&amp;rsquo;s Declaration Syntax》来具体介绍和说明情况。
为此煎鱼将参考并结合这篇官方资料，带大家一 &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
前段时间看到大家在吵一个话题，那就是 Go 语言的类型声明，抠知识抠的非常细了，就是为什么他要放在后面。
示例代码如下：
[&amp;hellip;] var a []string var b []string 其实在早年 Go 官方估计已经被问烦了，写过一篇《Go&amp;rsquo;s Declaration Syntax》来具体介绍和说明情况。
为此煎鱼将参考并结合这篇官方资料，带大家一 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/type-after/">为什么 Go 语言把类型放在后面？</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2021/12/31</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>前段时间看到大家在吵一个话题，那就是 Go 语言的类型声明，抠知识抠的非常细了，就是为什么他要放在后面。</p>
<p>示例代码如下：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">a</span> []<span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">b</span> []<span style="color:#66d9ef">string</span>
</span></span></code></pre></div><p>其实在早年 Go 官方估计已经被问烦了，写过一篇《<a href="https://go.dev/blog/declaration-syntax" title="Go's Declaration Syntax">Go&rsquo;s Declaration Syntax</a>》来具体介绍和说明情况。</p>
<p>为此煎鱼将参考并结合这篇官方资料，带大家一起了解为什么 Go 如此的 “与众不同” ，为什么要把类型放在后面。</p>
<h2 id="类型前置">类型前置</h2>
<p>在业内目前有不少知名语言，也采取的是在声明变量类型时，把类型定义在名字前面。像是 C、C++、C#、Java 等：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-c" data-lang="c"><span style="display:flex;"><span><span style="color:#66d9ef">int</span> x;
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">int</span> x <span style="color:#f92672">=</span> <span style="color:#ae81ff">100</span>;
</span></span></code></pre></div><p>基本的格式定义：&lt;data_type&gt; &lt;variable_list&gt;;。</p>
<p>上面的声明是一个简单的例子，如果更复杂一些，Go 官方还给出了著名的函数指针的例子：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-c" data-lang="c"><span style="display:flex;"><span><span style="color:#66d9ef">int</span> (<span style="color:#f92672">*</span>fp)(<span style="color:#66d9ef">int</span> a, <span style="color:#66d9ef">int</span> b);
</span></span></code></pre></div><p>更进一步，如果返回值也是个函数指针类型，就会变成：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-c" data-lang="c"><span style="display:flex;"><span><span style="color:#66d9ef">int</span> (<span style="color:#f92672">*</span>(<span style="color:#f92672">*</span>fp)(<span style="color:#66d9ef">int</span> (<span style="color:#f92672">*</span>)(<span style="color:#66d9ef">int</span>, <span style="color:#66d9ef">int</span>), <span style="color:#66d9ef">int</span>))(<span style="color:#66d9ef">int</span>, <span style="color:#66d9ef">int</span>)
</span></span></code></pre></div><p>这已经很难看出来是个 fp 的声明了。</p>
<h2 id="类型后置">类型后置</h2>
<p>前面所举例的类型前置的编程语言，很多都是 C 系列中的一者。类型后置的代表，分别有：Go、Rust、Scala、Kotlin 等。</p>
<p>其实在很多类型后置的编程语言种，会采取变量名+冒号+类型的方式出现。就像 Rust 一样：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-rust" data-lang="rust"><span style="display:flex;"><span><span style="color:#66d9ef">let</span> x: <span style="color:#66d9ef">i32</span>;
</span></span></code></pre></div><p>基本的格式定义：</p>
<pre tabindex="0"><code>x: int
p: pointer to int
a: array[3] of int
</code></pre><p>Go 官方参照了这类类型后置的设计，并且为了简洁，进一步去掉了冒号和一些关键字，变成：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">a</span> []<span style="color:#66d9ef">string</span>
</span></span></code></pre></div><p>我们再看回前面 fp 的声明的例子：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-c" data-lang="c"><span style="display:flex;"><span><span style="color:#66d9ef">int</span> (<span style="color:#f92672">*</span>(<span style="color:#f92672">*</span>fp)(<span style="color:#66d9ef">int</span> (<span style="color:#f92672">*</span>)(<span style="color:#66d9ef">int</span>, <span style="color:#66d9ef">int</span>), <span style="color:#66d9ef">int</span>))(<span style="color:#66d9ef">int</span>, <span style="color:#66d9ef">int</span>)
</span></span></code></pre></div><p>再对比 Go 语言中就变成了：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#a6e22e">f</span> <span style="color:#66d9ef">func</span>(<span style="color:#66d9ef">func</span>(<span style="color:#66d9ef">int</span>,<span style="color:#66d9ef">int</span>) <span style="color:#66d9ef">int</span>, <span style="color:#66d9ef">int</span>) <span style="color:#66d9ef">func</span>(<span style="color:#66d9ef">int</span>, <span style="color:#66d9ef">int</span>) <span style="color:#66d9ef">int</span>
</span></span></code></pre></div><p>两者一对比，Go 语言代码可读性确实更高一些。</p>
<h2 id="思考">思考</h2>
<h3 id="后置类别">后置类别</h3>
<p>在类型声明上，实际上分为：变量类型后置、函数返回值后置。两者共同构建了前置还是后置，总不能一个前置，一个后置吧，那得多么的难受。</p>
<p>上方 C 语言和 Go 语言函数指针的例子，所对比带来的代码可读性提高，其实本质上是由<strong>函数返回值后置</strong>所带来的。</p>
<p>和类型前置、后置没太多直接关系。</p>
<h3 id="核心思想">核心思想</h3>
<p>在类型后置上来讲，Go 官方核心思想是：<strong>这种声明方式（从左到右的风格）的一个优点是，当类型变得更加复杂时，它的效果非常好</strong>（One merit of this left-to-right style is how well it works as the types become more complex）。</p>
<p>Go 的变量名总是在前，在人的代码阅读上可以<strong>保持从左到右阅读</strong>，不需要像 C 语言一样在一大堆声明中用技巧找变量名对应的类型。</p>
<p><img src="https://files.mdnice.com/user/3610/b025d274-ae83-404c-8072-2776cd790708.png" alt="The Clockwise/Spiral Rule"></p>
<p>为此甚至有人写了篇 C 语言的顺时针读法《<a href="http://c-faq.com/decl/spiral.anderson.html" title="The Clockwise/Spiral Rule">The Clockwise/Spiral Rule</a>》，有兴趣可以阅读。</p>
<p>如此一对比，Go 语言的类型后置在复杂场景下与 C 语言的对比确实更好一些。</p>
<h3 id="其他因素">其他因素</h3>
<h4 id="类型推导">类型推导</h4>
<p>诸如在类型推导的形式上也会更直观：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-golang" data-lang="golang"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">s1</span> <span style="color:#f92672">:=</span> <span style="color:#e6db74">&#34;脑子进煎鱼了&#34;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> <span style="color:#a6e22e">s2</span> <span style="color:#66d9ef">string</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>也是一个可读性提高的问题。</p>
<h4 id="类型和名字谁更重要">类型和名字谁更重要</h4>
<p>不同设计者对谁更重要的理解也不一样。是类型更重要，还是名字更重要呢？</p>
<p>有的人认为是类型，有的人认为是名字。这就真的是千人千面，众口难调了。</p>
<h2 id="c-的后悔">C# 的后悔</h2>
<p>我们看看其他语言，C# 设计组成员之一，其实在《<a href="https://www.informit.com/articles/article.aspx?p=2425867" title="Sharp Regrets: Top 10 Worst C# Features">Sharp Regrets: Top 10 Worst C# Features</a>》中的第五点表达了个人对类型前置、后置的设计教训。</p>
<p><img src="https://files.mdnice.com/user/3610/6d5665b7-125f-4202-8742-c11c433566d7.png" alt=""></p>
<p>核心观点是：从编程和数学两方面来看，都有一个约定，即计算的结果在右侧表示，所以在类 C 语言中，类型在左侧是很奇怪的。</p>
<p>在设计时，C# 本来计划把类型注释放在右边。但考虑到类 C 语言，因此遵循了其他语言的惯例。</p>
<h2 id="总结">总结</h2>
<p>实际上该问题的研讨，在 2021 年的现在，大部分 case 都一一被反驳了。类型后置也不是一个与众不同的设计，很多语言都是如此。但既然要讨论 Go 语言，那更多的是站在设计者的角度去考虑。</p>
<p>结合 Go 所提供的官方资料，在当年的目的更多的是为了<strong>在遇到复杂类型定义时，能保持一定的代码可读性</strong>。</p>
<p>当然，这不可否认肯定包含 Go 开发团队的主观意识。有兴趣的可以具体挖挖背后的信息。</p>
<p>如果是你，<strong>你会把类型放在前面，还是后面呢，为什么</strong>？</p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/slice-leak/">Go 切片导致内存泄露，被坑两次了！</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/when-gc/">Go 什么时候会触发 GC？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/map-reset/">Go map 如何缩容？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/map-65/">面试官：为什么 Go 的负载因子是 6.5？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/slice-discuss/">Go 切片这道题，吵了一个下午！</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/slice-leak/"
                                                    rel="prev">Go 切片导致内存泄露，被坑两次了！</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/annotation/">Go：我有注解，Java：不，你没有！</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>